import { fileURLToPath, URL } from 'node:url'

import { defineConfig, loadEnv } from 'vite'
import Icons from 'unplugin-icons/vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { AntDesignVueResolver } from 'unplugin-vue-components/resolvers'

import { theme } from 'ant-design-vue'
const { defaultAlgorithm, defaultSeed } = theme
const mapToken = defaultAlgorithm(defaultSeed)

// https://vitejs.dev/config/
export default ({ mode }) => {
  return defineConfig({
    plugins: [
      vue(),
      vueJsx(),
      Icons({
        compiler: 'vue3',
        autoInstall: true
      }),
      AutoImport({
        dts: 'src/auto-imports.d.ts',
        imports: ['vue', 'vue-router'],
        eslintrc: {
          enabled: true,
          filepath: './.eslintrc-auto-import.json',
          globalsPropValue: true
        }
      }),
      Components({
        dts: 'src/components.d.ts',
        deep: true,
        dirs: ['src/components'],
        extensions: ['vue', 'tsx'],
        resolvers: [
          AntDesignVueResolver({
            importStyle: false
          })
        ]
      })
    ],
    build: {
      minify: 'terser',
      terserOptions: {
        compress: {
          drop_console: true,
          drop_debugger: true
        }
      },
      chunkSizeWarningLimit: 1500,
      rollupOptions: {
        output: {
          manualChunks(id) {
            if (id.includes('node_modules')) {
              return id.toString().split('node_modules/')[1].split('/')[0].toString()
            } else {
              return null
            }
          }
        }
      }
    },
    css: {
      preprocessorOptions: {
        less: {
          modifyVars: mapToken,
          javascriptEnabled: true
        }
      }
    },
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url))
      }
    },
    server: {
      host: '0.0.0.0',
      port: 5173, // 端口号
      open: false, // 是否自动打开浏览器
      proxy: {
        '^/sys': {
          target: loadEnv(mode, process.cwd()).VITE_API_URL,
          changeOrigin: true
        },
        '^/path/api': {
          target: loadEnv(mode, process.cwd()).VITE_API_URL,
          changeOrigin: true
        },
        '^/dict': {
          target: loadEnv(mode, process.cwd()).VITE_API_URL,
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/dict/, '/dict')
        },
        '^/eprofile-web': {
          target: loadEnv(mode, process.cwd()).VITE_API_URL_SERVE,
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/eprofile-web/, '')
        }
        // '^/eprofile-web': {
        //   target: loadEnv(mode, process.cwd()).VITE_API_URL,
        //   changeOrigin: true
        // }
      }
    }
  })
}
